Unit-4 & 5 QB Solution

Manish Patel

Dec 13, 2023

1. Check if a string is palindrome:

def is_palindrome(s):
    return s == s[::-1]

# Example usage
string_to_check = "radar"
print(is_palindrome(string_to_check))
True

2. Find length of a string in python:

string_length = len("Hello, World!")
print("Length of the string:", string_length)
Length of the string: 13

3. Find length of a string without using len function:

def find_length(s):
    count = 0
    for char in s:
        count += 1
    return count

# Example usage

string_length = find_length("Hello, World!")
print("Length of the string:", string_length)
Length of the string: 13

4. Count uppercase and lowercase letters:

def count_case(s):
    uppercase_count = sum(1 for char in s if char.isupper())
    lowercase_count = sum(1 for char in s if char.islower())
    return uppercase_count, lowercase_count

# Example usage
string_to_check = "Hello, World!"
upper, lower = count_case(string_to_check)
print("Uppercase count:", upper)
print("Lowercase count:", lower)
Uppercase count: 2
Lowercase count: 8

5. Demonstrate negative index in a Tuple:

my_tuple = (1, 2, 3, 4, 5)
print("Last element:", my_tuple[-1])
print("Second to last element:", my_tuple[-2])
Last element: 5
Second to last element: 4

6. Remove I’th character from string:

def remove_ith_char(s, i):
    return s[:i] + s[i+1:]

# Example usage
original_string = "Hello, World!"
index_to_remove = 7
new_string = remove_ith_char(original_string, index_to_remove)
print("Original String:", original_string)
print("String after removing character at index", index_to_remove, ":", new_string)
Original String: Hello, World!
String after removing character at index 7 : Hello, orld!

7. Create a string made of first, middle, and last character:

def create_string_from_chars(s):
    return s[0] + s[len(s)//2] + s[-1]

# Example usage
original_string = "Hello"
new_string = create_string_from_chars(original_string)
print("Original String:", original_string)
print("New String:", new_string)
Original String: Hello
New String: Hlo

8. Find all occurrences of a substring ignoring case:

def find_occurrences(s, sub):
    return [i for i in range(len(s)) if s[i:i+len(sub)].lower() == sub.lower()]

# Example usage
main_string = "Hello, hello, hEllo"
substring = "hello"
occurrences = find_occurrences(main_string, substring)
print("Occurrences of substring:", occurrences)
Occurrences of substring: [0, 7, 14]

9. Calculate the sum and average of digits in a string:

def sum_and_avg_digits(s):
    digits = [int(char) for char in s if char.isdigit()]
    sum_digits = sum(digits)
    avg_digits = sum_digits / len(digits) if len(digits) > 0 else 0
    return sum_digits, avg_digits

# Example usage
string_with_digits = "abc12345"
sum_digits, avg_digits = sum_and_avg_digits(string_with_digits)
print("Sum of digits:", sum_digits)
print("Average of digits:", avg_digits)
Sum of digits: 15
Average of digits: 3.0

10. Reverse a given string:

original_string = "Hello, World!"
reversed_string = original_string[::-1]
print("Original String:", original_string)
print("Reversed String:", reversed_string)
Original String: Hello, World!
Reversed String: !dlroW ,olleH

12. Uppercase Half String:

def uppercase_half_string(s):
    halfway = len(s) // 2
    return s[:halfway].upper() + s[halfway:]

# Example usage
input_string = "hello world"
result = uppercase_half_string(input_string)
print("Uppercase Half String:", result)
Uppercase Half String: HELLO world

13. Capitalize first and last character of each word:

def capitalize_first_last(s):
    words = s.split()
    modified_words = [word[0].capitalize() + word[1:-1] + word[-1].capitalize() if len(word) > 1 else word.capitalize() for word in words]
    return ' '.join(modified_words)

# Example usage
input_string = "hello world"
result = capitalize_first_last(input_string)
print("Modified String:", result)
Modified String: HellO WorlD

14. Create a string made of the middle three characters:

def middle_three_chars(s):
    middle = len(s) // 2
    return s[middle-1:middle+2]

# Example usage
input_string = "abcdef"
result = middle_three_chars(input_string)
print("Middle Three Characters:", result)
Middle Three Characters: cde

15. Check if two strings are balanced:

def are_strings_balanced(s1, s2):
    return set(s1) <= set(s2)

# Example usage
string1 = "abc"
string2 = "cba"
result = are_strings_balanced(string1, string2)
print("Are strings balanced?", result)
Are strings balanced? True

16. Split a string on hyphens:

input_string = "hello-world-how-are-you"
split_string = input_string.split('-')
print("Split String:", split_string)
Split String: ['hello', 'world', 'how', 'are', 'you']

Write a Python program using function to shift the decimal digits n places to the left, wrapping the extra digits around. If shift > the number of digits of n, then reverse the string.

Note: Function will take two parameters: 1. The number 2. How much shift user want

Example:
Input: n=12345 shift=1
Output: Result=23451

Input: n=12345 shift=3
Output: Result=45123

Input: n=12345 shift=5
Output: Result=12345

Input: n=12345 shift=6
Output: Result=54321

def shift_decimal_digits(number, shift):
    str_number = str(number)
    num_digits = len(str_number)

    # Reverse the string if shift > number of digits
    if shift > num_digits:
        result = str_number[::-1]
    else:
        # Shift the digits to the left, wrapping around
        result = str_number[shift:] + str_number[:shift]

    return int(result)

# Example usage
n1 = 12345
shift1 = 1
result1 = shift_decimal_digits(n1, shift1)
print(f"Input: n={n1} shift={shift1}\nOutput: Result={result1}")

n2 = 12345
shift2 = 3
result2 = shift_decimal_digits(n2, shift2)
print(f"\nInput: n={n2} shift={shift2}\nOutput: Result={result2}")

n3 = 12345
shift3 = 5
result3 = shift_decimal_digits(n3, shift3)
print(f"\nInput: n={n3} shift={shift3}\nOutput: Result={result3}")

n4 = 12345
shift4 = 6
result4 = shift_decimal_digits(n4, shift4)
print(f"\nInput: n={n4} shift={shift4}\nOutput: Result={result4}")
Input: n=12345 shift=1
Output: Result=23451

Input: n=12345 shift=3
Output: Result=45123

Input: n=12345 shift=5
Output: Result=12345

Input: n=12345 shift=6
Output: Result=54321

Write a Python programme that accepts a string and calculate the number of uppercase letters, lowercase letters and number of digits.

For example,

Input: Hello Pyth@n is 100% easy

Output:

Uppercase letters : 2
Lowercase letters : 14
Digits : 3

def count_characters(string):
    uppercase_count = sum(1 for char in string if char.isupper())
    lowercase_count = sum(1 for char in string if char.islower())
    digit_count = sum(1 for char in string if char.isdigit())

    print("Uppercase letters:", uppercase_count)
    print("Lowercase letters:", lowercase_count)
    print("Digits:", digit_count)

# Example usage
input_string = "Hello Pyth@n is 100% easy"
count_characters(input_string)
Uppercase letters: 2
Lowercase letters: 14
Digits: 3

Write a python program to check the validity of a Password.

Primary conditions for password validation:

1. Minimum 8 characters.
2. The alphabet must be between [a-z]
3. At least one alphabet should be of Upper Case [A-Z]
4. At least 1 number or digit between [0-9]
5. At least 1 character from [ _ or @ or $]
    Examples:
    Input: Ram@_f1234
    Output: Valid Password

    Input: Rama_fo$ab
    Output: Invalid Password
    Explanation: Number is missing

    Input: Rama#fo9c
    Output: Invalid Password
    Explanation: Must consist from _ or @ or \$
    

def is_valid_password(password):
    # Check the minimum length
    if len(password) < 8:
        return "Invalid Password: Minimum 8 characters required."

    # Check for at least one lowercase alphabet
    lowercase_found = False
    for char in password:
        if char.islower():
            lowercase_found = True
            break
    if not lowercase_found:
        return "Invalid Password: At least one lowercase alphabet required."

    # Check for at least one uppercase alphabet
    uppercase_found = False
    for char in password:
        if char.isupper():
            uppercase_found = True
            break
    if not uppercase_found:
        return "Invalid Password: At least one uppercase alphabet required."

    # Check for at least one digit
    digit_found = False
    for char in password:
        if char.isdigit():
            digit_found = True
            break
    if not digit_found:
        return "Invalid Password: At least one digit required."

    # Check for at least one of the special characters (_ or @ or $)
    special_char_found = False
    for char in password:
        if char in '_@$':
            special_char_found = True
            break
    if not special_char_found:
        return "Invalid Password: At least one of _ or @ or $ required."

    # If all conditions are met, the password is valid
    return "Valid Password"

# Example usage
password1 = "Ram@_f1234"
print(f"Input: {password1}\nOutput: {is_valid_password(password1)}")

password2 = "Rama_fo$ab"
print(f"\nInput: {password2}\nOutput: {is_valid_password(password2)}")

password3 = "Rama#fo9c"
print(f"\nInput: {password3}\nOutput: {is_valid_password(password3)}")
Input: Ram@_f1234
Output: Valid Password

Input: Rama_fo$ab
Output: Invalid Password: At least one digit required.

Input: Rama#fo9c
Output: Invalid Password: At least one of _ or @ or $ required.

Write a Python program to return another string similar to the input string, but with its case inverted.

For example, input of “Mr. Ed” will result in “mR. eD” as the output string. Note: Use of built in swapcase function is prohibited.

def invert_case(input_string):
    inverted_string = ""
    for char in input_string:
        if char.isupper():
            inverted_string += char.lower()
        elif char.islower():
            inverted_string += char.upper()
        else:
            inverted_string += char

    return inverted_string

# Example usage
input_string = "Mr. Ed"
output_string = invert_case(input_string)
print("Input string:", input_string)
print("Output string:", output_string)
Input string: Mr. Ed
Output string: mR. eD

Dr. Prasad is opening a new world class hospital in a small town designed to be the first preference of the patients in the city. Hospital has N rooms of two types – with TV and without TV, with daily rates of R1 and R2 respectively. However, from his experience Dr. Prasad knows that the number of patients is not constant throughout the year, instead it follows a pattern. The number of patients on any given day of the year is given by the following formula – (6-M)^2 + |D-15| , where M is the number of month (1 for jan, 2 for feb …12 for dec) and D is the date (1,2…31). All patients prefer without TV rooms as they are cheaper, but will opt for with TV rooms only if without TV rooms are not available. Hospital has a revenue target for the first year of operation. Given this target and the values of N, R1 and R2 you need to identify the number of TVs the hospital should buy so that it meets the revenue target. Assume the Hospital opens on 1st Jan and year is a non-leap year.

  • Constraints

  • Hospital opens on 1st Jan in an ordinary year

  • 5 <= Number of rooms <= 100

  • 500 <= Room Rates <= 5000

  • 0 <= Target revenue < 90000000

Input Format:  
- First line provides an integer N that denotes the number of rooms in the hospital.
- Second line provides the rates of rooms with TV (R1).
- Third line provides the rates of rooms without TV (R2).
- Fourth line provides the revenue target.

Output:
    Minimum number of TVs the hospital needs to buy to meet its revenue target. If it cannot achieve its target, print the total number of rooms in the hospital.
Test Case
Example-1 :
Input
20
1500 
1000
7000000
Output
14

def getPatients(M, D):
    diff = 6 - M
    patient_count = (diff * diff)

    if D >= 15:
        patient_count += (D - 15)
    else:
        patient_count += (15 - D)

    return patient_count

def countTVs(total_rooms, revenue_tv, revenue_no_tv, target_revenue):
    days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    for tv_count in range(total_rooms + 1):
        current_target = 0

        for month in range(1, 13):
            for day in range(1, 1 + days_in_month[month]):
                patients = getPatients(month, day)
                patients = min(patients, total_rooms)

                if patients <= total_rooms - tv_count:
                    current_target += patients * revenue_no_tv
                else:
                    tv_patients = patients - (total_rooms - tv_count)
                    current_target += (total_rooms - tv_count) * revenue_no_tv + tv_patients * revenue_tv

        if current_target >= target_revenue:
            break

    print(min(tv_count, total_rooms))

# Driver Code
total_rooms = 20
revenue_tv = 1500
revenue_no_tv = 1000
target_revenue = 7000000

countTVs(total_rooms, revenue_tv, revenue_no_tv, target_revenue)
14

Write a Python program to create a Caesar encryption.

Note: In cryptography, a Caesar cipher, also known as Caesar’s cipher, the shift cipher, Caesar’s code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a right shift of 3, A would be replaced by D, E would become H, and so on. The method is named after Julius Caesar, who used it in his private correspondence.

For Example:

Input Text  : LJIET ENG
Shift : 3
Cipher:  OMLHW HQJ

def encrypt(key, message):
    message = message.upper()
    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ""

    for letter in message:
        if letter in alpha: #if the letter is actually a letter
            #find the corresponding ciphertext letter in the alphabet
            letter_index = (alpha.find(letter) + key) % len(alpha)

            result = result + alpha[letter_index]
        else:
            result = result + letter

    return result

def decrypt(key, message):
    message = message.upper()
    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ""

    for letter in message:
        if letter in alpha: #if the letter is actually a letter
            #find the corresponding ciphertext letter in the alphabet
            letter_index = (alpha.find(letter) - key) % len(alpha)

            result = result + alpha[letter_index]
        else:
            result = result + letter

    return result

# Example usage
message = "LJIET ENG"
key = 3
cipher_text = encrypt(key, message)

print("Input Text  :", message)
print("Shift        :", key)
print("Cipher       :", cipher_text)
Input Text  : LJIET ENG
Shift        : 3
Cipher       : OMLHW HQJ

Write a program to check if two strings are balanced. For example, strings s1 and s2 are balanced if all the characters in the s1 are present in s2 and length of s1 & s2 should be same. The character’s position doesn’t matter.

Example :

s1 = hello
s2 = olleh
Balanced

def are_strings_balanced(s1, s2):
    # Check if lengths are equal
    if len(s1) != len(s2):
        return False

    # Check if all characters in s1 are present in s2
    for char in s1:
        if char not in s2:
            return False

    return True

# Example usage
string1 = "hello"
string2 = "olleh"
result = are_strings_balanced(string1, string2)

if result:
    print(f"{string1} and {string2} are Balanced")
else:
    print(f"{string1} and {string2} are Not Balanced")
hello and olleh are Balanced

UNIT 5

Write a python code to demonstrate any three methods of list

# Method 1: append()
my_list = [1, 2, 3]
my_list.append(4)
print("Method 1 - append:", my_list)

# Method 2: extend()
my_list.extend([5, 6])
print("Method 2 - extend:", my_list)

# Method 3: remove()
my_list.remove(3)
print("Method 3 - remove:", my_list)
Method 1 - append: [1, 2, 3, 4]
Method 2 - extend: [1, 2, 3, 4, 5, 6]
Method 3 - remove: [1, 2, 4, 5, 6]

Write a python code to explain map in Python program.

# Example 1: Doubling each element in a list using map
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print("Doubled Numbers:", doubled_numbers)

# Example 2: Converting strings to uppercase using map
words = ["apple", "banana", "cherry"]
uppercase_words = list(map(str.upper, words))
print("Uppercase Words:", uppercase_words)
Doubled Numbers: [2, 4, 6, 8, 10]
Uppercase Words: ['APPLE', 'BANANA', 'CHERRY']

Write a python code to explain filter in Python program.

# Example 1: Filtering even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", even_numbers)

# Example 2: Filtering words with length greater than 5
words = ["apple", "banana", "cherry", "date", "elderberry"]
long_words = list(filter(lambda word: len(word) > 5, words))
print("Long Words:", long_words)
Even Numbers: [2, 4, 6, 8]
Long Words: ['banana', 'cherry', 'elderberry']

Write a Python program to print the even numbers from a given list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print("Even Numbers:", even_numbers)
Even Numbers: [2, 4, 6, 8, 10]

Write a Python Program to print the largest even number in a list.

numbers = [1, 5, 8, 3, 12, 6, 10, 7]
even_numbers = [num for num in numbers if num % 2 == 0]
largest_even = max(even_numbers)
print("Largest Even Number:", largest_even)
Largest Even Number: 12

Write a Python Program to print the largest odd number in a list.

numbers = [1, 5, 8, 3, 12, 6, 10, 7]
odd_numbers = [num for num in numbers if num % 2 != 0]
largest_odd = max(odd_numbers)
print("Largest Odd Number:", largest_odd)
Largest Odd Number: 7

Write a Python program to swap first and last element of the list.

my_list = [1, 2, 3, 4, 5]
my_list[0], my_list[-1] = my_list[-1], my_list[0]
print("Swapped List:", my_list)
Swapped List: [5, 2, 3, 4, 1]

Write a Python program to find the sum of all the elements in the list.

numbers = [1, 2, 3, 4, 5]
sum_of_elements = sum(numbers)
print("Sum of Elements:", sum_of_elements)
Sum of Elements: 15

Write a Python function to sum all the numbers in a list

def sum_of_list(numbers):
    return sum(numbers)

numbers = [1, 2, 3, 4, 5]
result = sum_of_list(numbers)
print("Sum of Elements (Function):", result)
Sum of Elements (Function): 15

Write a Python program of Reversing a List.

my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print("Reversed List:", reversed_list)
Reversed List: [5, 4, 3, 2, 1]

Write a Python program to Merging two Dictionaries

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print("Merged Dictionary:", merged_dict)
Merged Dictionary: {'a': 1, 'b': 3, 'c': 4}

Write a Python program to calculate the sum of the positive and negative numbers of a given list of numbers using lambda function.

numbers = [1, -2, 3, -4, 5, -6]
sum_positive = lambda x: sum(num for num in x if num > 0)
sum_negative = lambda x: sum(num for num in x if num < 0)

print("Sum of Positive Numbers:", sum_positive(numbers))
print("Sum of Negative Numbers:", sum_negative(numbers))
Sum of Positive Numbers: 9
Sum of Negative Numbers: -12

Write a Python program to rearrange positive and negative numbers in a given array using Lambda.

numbers = [1, -2, 3, -4, 5, -6]
arrange_numbers = lambda x: sorted(x, key=lambda num: (num >= 0, num))

arranged_numbers = arrange_numbers(numbers)
print("Rearranged Numbers:", arranged_numbers)
Rearranged Numbers: [-6, -4, -2, 1, 3, 5]

Write a Python program to find numbers divisible by nineteen or thirteen from a list of numbers using Lambda.

numbers = [19, 26, 39, 52, 65, 13, 78]
divisible_by_nineteen_or_thirteen = lambda x: [num for num in x if num % 19 == 0 or num % 13 == 0]

result = divisible_by_nineteen_or_thirteen(numbers)
print("Numbers Divisible by Nineteen or Thirteen:", result)
Numbers Divisible by Nineteen or Thirteen: [19, 26, 39, 52, 65, 13, 78]

Write a Python function to implement linear search algorithm.

Linear search is also called as sequential search algorithm. It is the simplest searching algorithm. In Linear search, we simply traverse the list completely and match each element of the list with the item whose location is to be found. If the match is found, then the location of the item is returned; otherwise, the algorithm returns NULL. The following is linear search algorithm: Given a list L of n elements with values or records L0 …. Ln−1, and target value T, the following subroutine uses linear search to find the index of the target T in L.

1. Set i to 0.
2. If Li = T, the search terminates successfully; return i.
3. Increase i by 1.
4. If i < n, go to step 2. Otherwise, the search terminates unsuccessfully.

 
Input: 
Enter the list of numbers: 5 4 3 2 1 10 11 2
The number to search for: 1

Output:
1 was found at index 4.

def linear_search(lst, target):
    for i, num in enumerate(lst):
        if num == target:
            return i
    return None

# Example usage
user_input = input("Enter the list of numbers separated by spaces: ")
numbers = list(map(int, user_input.split()))

target_number = int(input("The number to search for: "))

result = linear_search(numbers, target_number)

if result is not None:
    print(f"{target_number} was found at index {result}.")
else:
    print(f"{target_number} was not found in the list.")
Enter the list of numbers separated by spaces: 1 2 3 4 5
The number to search for: 5
5 was found at index 4.

Given a list of elements, write a python program to perform grouping of similar elements, as different key-value list in dictionary. Print the dictionary sorted in descending order of frequency of the elements.

Note: To perform the sorting, use the sorted function by converting the dictionary into a list of tuples. After sorting, convert the list of tuples back into a dictionary and print it. Input : test_list = [4, 6, 6, 4, 2, 2, 4, 8, 5, 8] Output : {4: [4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]} Explanation : Similar items grouped together on occurrences.

Input : test_list = [7, 7, 7, 7] Output : {7 : [7, 7, 7, 7]} Explanation : Similar items grouped together on occurrences.

def group_elements(lst):
    grouped_dict = {}

    for elem in lst:
        if elem in grouped_dict:
            grouped_dict[elem].append(elem)
        else:
            grouped_dict[elem] = [elem]

    # Sort the dictionary by frequency in descending order
    sorted_list = sorted(grouped_dict.items(), key=lambda x: len(x[1]), reverse=True)

    # Convert the sorted list back to a dictionary
    sorted_dict = dict(sorted_list)

    return sorted_dict

# Example usage
test_list = [4, 6, 6, 4, 2, 2, 4, 8, 5, 8]
result_dict = group_elements(test_list)

print("Input List:", test_list)
print("Output Dictionary:", result_dict)
Input List: [4, 6, 6, 4, 2, 2, 4, 8, 5, 8]
Output Dictionary: {4: [4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]}

A digital image in a computer is represented by a pixels matrix. Each image processing operation in a computer may be observed as an operation on the image matrix. Suppose you are given an N x N 2D matrix A (in the form of a list) representing an image. Write a Python program to rotate this image by 90 degrees (clockwise) by rotating the matrix 90 degree clockwise. Write proper code to take input of N from the user and then to take input of an N x N matrix from the user. Rotate the matrix by 90 degree clockwise and then print the rotated matrix.

Note: You are not allowed to use an extra iterable like list, tuple, etc. to do this. You need to make changes in the given list A itself. Your program should be able to handle any N x N matrix from N = 1 to N = 20.

## def rotate_matrix_90_degrees(matrix):
    N = len(matrix)

    # Transpose the matrix
    for i in range(N):
        for j in range(i, N):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

    # Reverse each row
    for i in range(N):
        matrix[i].reverse()

# Get the size of the matrix from the user
N = int(input("Enter the size of the matrix (N): "))

# Get the matrix input from the user
matrix = []
print("Enter the matrix (each row on a new line):")
for _ in range(N):
    row = list(map(int, input().split()))
    matrix.append(row)

# Rotate the matrix by 90 degrees clockwise
rotate_matrix_90_degrees(matrix)

# Print the rotated matrix
print("Rotated Matrix:")
for row in matrix:
    print(" ".join(map(str, row)))

Write a Program to Print Longest Common Prefix from a given list of strings. The longest common prefix for list of strings is the common prefix (starting of string) between all strings. For example, in the given list [“apple”, “ape”, “zebra”], there is no common prefix because the 2 most dissimilar strings of the list “ape” and “zebra” do not share any starting characters. If there is no common prefix between all strings in the list than return -1.

For example,
Input list: ["lessonplan", "lesson","lees", "length"]
The longest Common Prefix is: le

Input list: ["python","pythonprogramming","pythonlist"]
The longest Common Prefix is: python

Input list: ["lessonplan", "lesson","ees", "length"]
The longest Common Prefix is: -1

def longest_common_prefix(str_list):
    if not str_list:
        return -1

    str_list.sort()

    prefix = ""
    for i in range(len(str_list[0])):
        char = str_list[0][i]
        prefix_match = True

        for s in str_list:
            if not s.startswith(prefix + char):
                prefix_match = False
                break

        if prefix_match:
            prefix += char
        else:
            break

    return prefix if prefix else -1

# Example usage
input_list1 = ["lessonplan", "lesson", "lees", "length"]
result1 = longest_common_prefix(input_list1)
print("Input list:", input_list1)
print("The longest Common Prefix is:", result1)

input_list2 = ["python", "pythonprogramming", "pythonlist"]
result2 = longest_common_prefix(input_list2)
print("\nInput list:", input_list2)
print("The longest Common Prefix is:", result2)

input_list3 = ["lessonplan", "lesson", "ees", "length"]
result3 = longest_common_prefix(input_list3)
print("\nInput list:", input_list3)
print("The longest Common Prefix is:", result3)
Input list: ['lees', 'length', 'lesson', 'lessonplan']
The longest Common Prefix is: le

Input list: ['python', 'pythonlist', 'pythonprogramming']
The longest Common Prefix is: python

Input list: ['ees', 'length', 'lesson', 'lessonplan']
The longest Common Prefix is: -1

RAIL-FENCE ENCRYPTION

One of the ways to encrypt a string is by rearranging its characters by certain rules, they are broken up by threes, fours or something larger. For instance, in the case of threes, the string ‘secret message’ would be broken into three groups. The first group is sr sg, the characters at indices 0, 3, 6, 9 and 12. The second group is eemse, the characters at indices 1, 4, 7, 10, and 13. The last group is ctea, the characters at indices 2, 5, 8, and 11. The encrypted message is sr sgeemsectea. If the string ‘secret message’ would be broken into four groups. The first group is seeg, the characters at indices 0, 4, 8 and 12. The second group is etse, the characters at indices 1, 5, 9 and 13. The third group is c s, the characters at indices 2, 6 and 10. The fourth group is rma, the characters at indices 3, 7 and 11. The encrypted message is seegetsec srma.

PART-A RAIL FENCE ENCRYPTION

def encrypt_rail_fence(message, num_rails=3):
    rails = ['' for _ in range(num_rails)]

    for i, char in enumerate(message):
        rail_index = i % num_rails
        rails[rail_index] += char

    encrypted_message = ''
    for rail in rails:
        encrypted_message += rail

    return encrypted_message

# Example usage:
user_input = input("Enter the string to encrypt: ")
encrypted_message = encrypt_rail_fence(user_input, 5)
print("Encrypted message:", encrypted_message)
Enter the string to encrypt: Hi hello how are you going to learn python in this semester of engineering
Encrypted message: Hloe gl o  sogrilw g epntstfii o yotay hee nnh aoiortiimreegehrun nhnse ne

PART-B RAIL FENCE DECRYPTION

def decrypt_rail_fence(encrypted_message, num_rails=3):
    rail_length = len(encrypted_message) // num_rails
    rails = ['' for _ in range(num_rails)]

    # Distribute characters to the rails
    for i in range(num_rails):
        if i < len(encrypted_message) % num_rails:
            rails[i] = encrypted_message[i * (rail_length + 1):(i + 1) * (rail_length + 1)]
        else:
            rails[i] = encrypted_message[i * rail_length + len(encrypted_message) % num_rails:
                                            (i + 1) * rail_length + len(encrypted_message) % num_rails]

    # Reconstruct the original message
    decrypted_message = ''
    for i in range(rail_length + 1):
        for j in range(num_rails):
            if i < len(rails[j]):
                decrypted_message += rails[j][i]

    return decrypted_message

# Example usage:
encrypted_input = input("Enter the string to decrypt: ")
decrypted_message = decrypt_rail_fence(encrypted_input, 5)
print("Decrypted message:", decrypted_message)
Enter the string to decrypt: Hloe gl o  sogrilw g epntstfii o yotay hee nnh aoiortiimreegehrun nhnse ne
Decrypted message: Hi hello how are you going to learn python in this semester of engineering

PART-C DICTIONARY CREATION

def create_word_dict(decrypted_message):
    # Split the decrypted message into words
    words = decrypted_message.split()

    # Create a dictionary with the first character of each word as the key
    word_dict = {}
    for word in words:
        first_char = word[0].lower()  # Convert to lowercase for case-insensitivity
        if first_char in word_dict:
            word_dict[first_char].append(word)
        else:
            word_dict[first_char] = [word]

    # Sort the dictionary based on the number of elements in each list in descending order
    sorted_word_dict = dict(sorted(word_dict.items(), key=lambda x: len(x[1]), reverse=True))

    return sorted_word_dict

# Example usage:
decrypted_input = input("Enter Decrypted Message: ")
word_dict = create_word_dict(decrypted_input)

print("Output:", word_dict)
Enter Decrypted Message: Hi hello how are you going to learn python in this semester of engineering
Output: {'h': ['Hi', 'hello', 'how'], 't': ['to', 'this'], 'a': ['are'], 'y': ['you'], 'g': ['going'], 'l': ['learn'], 'p': ['python'], 'i': ['in'], 's': ['semester'], 'o': ['of'], 'e': ['engineering']}

Write a python program to print all possible combinations from the three Digits and also count unique values inside a list and also find list product excluding duplicates and also find sum of list’s elements excluding duplicates.

Examples:

To print all possible combinations
Input: [1, 2, 3]
Output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

Count unique values inside a list

input = [1, 2, 3]
No of unique items are: 3

input = [1, 2, 2]
No of unique items are: 2

input = [2, 2, 2]
No of unique items are: 3

List product excluding duplicates

Input: [2, 3, 5]
Duplication removal list product: 30

Input: [2, 2, 3]
Duplication removal list product: 6

Sum of list’s elements excluding duplicates

Input: [1, 3, 5]
Output: 9

Input: [1, 2, 2]
Output: 3

# Function to print all possible combinations
def print_all_combinations(current, remaining):
    if not remaining:
        print(current)
        return
    seen = set()
    for i in range(len(remaining)):
        if remaining[i] not in seen:
            seen.add(remaining[i])
            print_all_combinations(current + [remaining[i]], remaining[:i] + remaining[i+1:])

# Function to count unique values inside a list
def count_unique_items(lst):
    unique_items = set()
    for item in lst:
        unique_items.add(item)
    print("No of unique items are:", len(unique_items))

# Function to find the product of list excluding duplicates
def product_excluding_duplicates(lst):
    unique_items = set(lst)
    product = 1
    for item in unique_items:
        product *= item
    return product

# Function to find the sum of list's elements excluding duplicates
def sum_excluding_duplicates(lst):
    unique_items = set(lst)
    return sum(unique_items)

# Example usage:
digits_input = [1, 2, 3]
print("All possible combinations:")
print_all_combinations([], digits_input)

list_input = [1, 2, 3]
count_unique_items(list_input)

list_input = [1, 2, 2]
count_unique_items(list_input)

list_input = [2, 2, 3]
count_unique_items(list_input)

print("Product excluding duplicates:", product_excluding_duplicates(list_input))
print("Sum excluding duplicates:", sum_excluding_duplicates(list_input))


print_all_combinations([],[2,2,2])
All possible combinations:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
No of unique items are: 3
No of unique items are: 2
No of unique items are: 2
Product excluding duplicates: 6
Sum excluding duplicates: 5
[2, 2, 2]

Use appropriate comment lines to divide subprograms. Also demonstrate the program with one example test case. (Example test input and output are given)

PART - A

Using map function, write a Python program to convert the given list into a tuple of strings. For the given input, the program must print the output as shown below - Input – [1,2,3,4] Output – (‘1’,’2’,’3’,’4’)

PART - B

Write a Python program that multiply each number of the given list with 10 using lambda function. For the given input, the program must print the output as shown below - Input – [1,2,3,4] Output – [10,20,30,40]

PART - C

Write a Python program that multiply all elements of the given list using reduce function and return the product. For the given input, the program must print the output as shown below - Input – [1,2,3,4] Output – 24 (which is 123*4)

PART - D

Create a python function countchar() that count the character of a string in a given string without using inbuilt functions. For the given input, the program must print the output as shown below -

Given input string – ‘hello’
countchar(‘l’)
Output : 2 

Create a python function findchar() that find the index of first occurrence of a character in a given string without using inbuilt functions. It should return -1 if it does not find the character. For the given input, the program must print the output as shown below -

Given input string – ‘helloe’
findchar(‘e’)
Output : 1 
findchar(‘z’)
Output : -1

from functools import reduce

# PART - A
def convert_to_tuple(input_list):
    """
    Convert the given list into a tuple of strings using map function.

    Parameters:
    input_list (list): The input list to be converted.

    Returns:
    tuple: The tuple of strings.
    """
    return tuple(map(str, input_list))

# PART - B
multiply_by_10 = lambda x: x * 10

def multiply_list_by_10(input_list):
    """
    Multiply each number of the given list with 10 using lambda function.

    Parameters:
    input_list (list): The input list to be multiplied.

    Returns:
    list: The list with elements multiplied by 10.
    """
    return list(map(multiply_by_10, input_list))

# PART - C
def multiply_all_elements(input_list):
    """
    Multiply all elements of the given list using reduce function and return the product.

    Parameters:
    input_list (list): The input list to calculate the product.

    Returns:
    int: The product of all elements.
    """
    return reduce(lambda x, y: x * y, input_list, 1)

# Example Test Case
input_list = [1, 2, 3, 4]

# PART - A
output_tuple = convert_to_tuple(input_list)
print("PART - A")
print(f"Input: {input_list}")
print(f"Output: {output_tuple}\n")

# PART - B
output_multiply_by_10 = multiply_list_by_10(input_list)
print("PART - B")
print(f"Input: {input_list}")
print(f"Output: {output_multiply_by_10}\n")

# PART - C
output_multiply_all_elements = multiply_all_elements(input_list)
print("PART - C")
print(f"Input: {input_list}")
print(f"Output: {output_multiply_all_elements}")

# PART - D
def countchar(input_string, char_to_count):
    """
    Count the occurrence of a character in a given string without using inbuilt functions.

    Parameters:
    input_string (str): The input string.
    char_to_count (str): The character to count in the input string.

    Returns:
    int: The count of the character in the input string.
    """
    count = 0
    for char in input_string:
        if char == char_to_count:
            count += 1
    return count

def findchar(input_string, char_to_find):
    """
    Find the index of the first occurrence of a character in a given string without using inbuilt functions.

    Parameters:
    input_string (str): The input string.
    char_to_find (str): The character to find in the input string.

    Returns:
    int: The index of the first occurrence of the character, or -1 if not found.
    """
    index = 0
    for char in input_string:
        if char == char_to_find:
            return index
        index += 1
    return -1

# Example Test Cases
input_string1 = 'hello'
char_count = 'l'
output_count = countchar(input_string1, char_count)
print(f"Input string: '{input_string1}'")
print(f"countchar('{char_count}'): {output_count}\n")

input_string2 = 'helloe'
char_to_find1 = 'e'
char_to_find2 = 'z'
output_find1 = findchar(input_string2, char_to_find1)
output_find2 = findchar(input_string2, char_to_find2)
print(f"Input string: '{input_string2}'")
print(f"findchar('{char_to_find1}'): {output_find1}")
print(f"findchar('{char_to_find2}'): {output_find2}")
PART - A
Input: [1, 2, 3, 4]
Output: ('1', '2', '3', '4')

PART - B
Input: [1, 2, 3, 4]
Output: [10, 20, 30, 40]

PART - C
Input: [1, 2, 3, 4]
Output: 24
Input string: 'hello'
countchar('l'): 2

Input string: 'helloe'
findchar('e'): 1
findchar('z'): -1

Write a Python program to calculate the sum of the positive and negative numbers of the below given list of numbers using lambda function.

Input    : m = [2, 4, -6, -9, 11, -12, 14, -5, 17]

Output :    Sum of the positive numbers:  -32
                   Sum of the negative numbers:  48

# Given list of numbers
m = [2, 4, -6, -9, 11, -12, 14, -5, 17]

# Lambda function to filter positive numbers
positive_numbers = lambda x: x > 0

# Lambda function to filter negative numbers
negative_numbers = lambda x: x < 0

# Calculate the sum of positive numbers using lambda function
sum_positive = sum(filter(positive_numbers, m))

# Calculate the sum of negative numbers using lambda function
sum_negative = sum(filter(negative_numbers, m))

# Output the results
print(f"Input: {m}")
print(f"Sum of the positive numbers: {sum_positive}")
print(f"Sum of the negative numbers: {sum_negative}")
Input: [2, 4, -6, -9, 11, -12, 14, -5, 17]
Sum of the positive numbers: 48
Sum of the negative numbers: -32

Create a python program which takes password as input and a function which checks whether the given password is valid or not under following conditions without using the RegEx module in Python language.

Conditions required for a valid password:

  1. Password strength should be at least 8 characters long
  2. Password should contain at least one uppercase and one lowercase character.
  3. Password must have at least one number.

# User input for the password
password = input("Enter a password: ")

# Check condition 1: Password length should be at least 8 characters
if len(password) < 8:
    print("Invalid Password: Password should be at least 8 characters long.")
else:
    # Check condition 2: Password should contain at least one uppercase and one lowercase character
    has_uppercase = False
    has_lowercase = False
    for char in password:
        if char.isupper():
            has_uppercase = True
        elif char.islower():
            has_lowercase = True

    # Check condition 3: Password must have at least one number
    has_digit = False
    for char in password:
        if char.isdigit():
            has_digit = True

    # Validate the password based on all conditions
    if has_uppercase and has_lowercase and has_digit:
        print("Valid Password")
    else:
        print("Invalid Password: Password should contain at least one uppercase and one lowercase character, and one number.")
Enter a password: Helloworld12
Valid Password

Write a python program with user defined function that reads the words from paragraph and stores them as keys in a dictionary and count the frequency of it as a value

For Example:

Input string: “Dog the quick brown fox jumps over the lazy dog”

Output: {'the': 2, 'jumps': 1, 'brown': 1, 'lazy': 1, 'fox': 1, 'over': 1, 'quick': 1, 'dog': 2}

def count_word_frequency(paragraph):
    """
    Count the frequency of words in a paragraph and store in a dictionary.

    Parameters:
    paragraph (str): The input paragraph.

    Returns:
    dict: A dictionary with words as keys and their frequencies as values.
    """
    word_frequency = {}
    words = paragraph.split()

    for word in words:
        # Remove punctuation (assuming simple cases with only letters)
        word = word.strip('.,!?')

        # Convert word to lowercase for case-insensitive counting
        word = word.lower()

        # Update the dictionary with word frequencies
        word_frequency[word] = word_frequency.get(word, 0) + 1

    return word_frequency

# Example usage
input_paragraph = "Dog the quick brown fox jumps over the lazy dog"
output_dict = count_word_frequency(input_paragraph)

# Output the result
print(f"Input paragraph: '{input_paragraph}'")
print("Output:", output_dict)
Input paragraph: 'Dog the quick brown fox jumps over the lazy dog'
Output: {'dog': 2, 'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1}

Write a python Program to check entered password by user is correct or not. Entered password is correct if it has upper character, lower character , digits (but not more than 3 digits) ,special character and length is greater than or equal to eight and less than equal to fifteen. Get the digits from entered password and convert it in to number and then convert it in to English Word .

Example:
case 1
pw= R@m@3fa1tu9e$
Valid Password
num= 319
three hundred and nineteen

case 2
pw= S@m@6a1tue$
Valid Password
num= 61
sixty-one

case 3
pw= S@m@6a26u8$
Invalid Password

def is_valid_password(password):
    """
    Check if the entered password is correct and convert digits to English words.

    Parameters:
    password (str): The input password.

    Returns:
    tuple: A tuple containing a boolean indicating whether the password is valid and the converted digits.
    """
    # Check conditions for a valid password
    has_upper = False
    has_lower = False
    digit_count = 0
    has_special = False

    for char in password:
        if char.isupper():
            has_upper = True
        elif char.islower():
            has_lower = True
        elif char.isdigit():
            digit_count += 1
        elif char in "!@#$%^&*()-_=+[]{}|;:'\",.<>/?`~":
            has_special = True

    if (
        has_upper
        and has_lower
        and 1 <= digit_count <= 3
        and has_special
        and 8 <= len(password) <= 15
    ):
        # Extract digits from the password
        digits = ''
        for char in password:
            if char.isdigit():
                digits += char

        # Convert digits to English words
        num_in_words = convert_to_words(int(digits))

        return True, digits, num_in_words
    else:
        return False, None, None

def convert_to_words(num):
    """
    Convert a number to its English word representation.

    Parameters:
    num (int): The input number.

    Returns:
    str: The English word representation of the number.
    """
    # Define lists for unit and tens places
    units = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    teens = ["", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
    tens = ["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

    # Convert each digit place to English words
    def convert_below_hundred(n):
        if n < 10:
            return units[n]
        elif 10 < n < 20:
            return teens[n - 10]
        else:
            return tens[n // 10] + ' ' + units[n % 10]

    if num == 0:
        return "zero"

    # Convert each group of three digits to English words
    result = ''
    if num >= 100:
        result += units[num // 100] + ' hundred '

    result += convert_below_hundred(num % 100)

    return result.strip()

# Example usage
password1 = "R@m@3fa1tu9e$"
valid1, digits1, num_in_words1 = is_valid_password(password1)
print(f"case 1\npw= {password1}")
if valid1:
    print("Valid Password")
    print(f"num= {digits1}")
    print(f"{num_in_words1}")
else:
    print("Invalid Password")

password2 = "S@m@6a1tue$"
valid2, digits2, num_in_words2 = is_valid_password(password2)
print(f"\ncase 2\npw= {password2}")
if valid2:
    print("Valid Password")
    print(f"num= {digits2}")
    print(f"{num_in_words2}")
else:
    print("Invalid Password")

password3 = "S@m@6a26u8$"
valid3, _, _ = is_valid_password(password3)
print(f"\ncase 3\npw= {password3}")
if valid3:
    print("Valid Password")
else:
    print("Invalid Password")
case 1
pw= R@m@3fa1tu9e$
Valid Password
num= 319
three hundred nineteen

case 2
pw= S@m@6a1tue$
Valid Password
num= 61
sixty one

case 3
pw= S@m@6a26u8$
Invalid Password

Write a Python Program using function to count number of strings where the string length is 3 or more and the first and last character are same from a given list of string.

Example :

Input: ['abc','xyz','aba','2112','123451','12345']
Output: 3

def count_strings_with_same_ends(strings):
    """
    Count the number of strings with length 3 or more, and the first and last character are the same.

    Parameters:
    strings (list): List of strings.

    Returns:
    int: Number of strings meeting the specified conditions.
    """
    count = 0

    for string in strings:
        if len(string) >= 3 and string[0] == string[-1]:
            count += 1

    return count

# Example usage
input_strings = ['abc', 'xyz', 'aba', '2112', '123451', '12345']
result = count_strings_with_same_ends(input_strings)

# Output the result
print(f"Input strings: {input_strings}")
print(f"Number of strings with the same first and last character: {result}")
Input strings: ['abc', 'xyz', 'aba', '2112', '123451', '12345']
Number of strings with the same first and last character: 3

Given a list L of size N. You need to count the number of special elements in the given list. An element is special if removal of that element makes the list balanced. The list will be balanced if sum of even index elements is equal to the sum of odd elements. Also print the updated lists after removal of special elements.

Example 1:
Input: 
L=[5, 5, 2, 5, 8]

Output:
Original List: [5, 5, 2, 5, 8]
Index to be removed is: 0
List after removing index 0 : [5, 2, 5, 8]

Original List: [5, 5, 2, 5, 8]
Index to be removed is: 1
List after removing index 1 : [5, 2, 5, 8]

Total number of special elements: 2

Explaination:
If we delete L[0] or L[1], list will be balanced.
[5, 2, 5, 8]
(5+5) = (2+8)
So L[0] and L[1] are special elements, So Count is 2.
After removal of the special elements, list will be: [5, 2, 5, 8]

Example 2:

Input:
L=[2,1,6,4]

Output:
Original List: [2, 1, 6, 4]
Index to be removed is: 1
List after removing index 1 : [2, 6, 4]
Total Number of Special elements: 1

Explaination:
If we delete L[1] from list : [2,6,4]
(2+4)  =  (6)
Here only 1 special element. So Count is 1.
After removal of special element, list will be : [2,6,4]

def is_balanced(lst):
    # Function to check if a list is balanced
    return sum(lst[::2]) == sum(lst[1::2])

def count_special_elements(lst):
    # Function to count special elements and print updated lists
    count = 0
    for i in range(len(lst)):
        temp_lst = lst.copy()
        removed_element = temp_lst.pop(i)
        if is_balanced(temp_lst):
            count += 1
            print(f"Original List: {lst}")
            print(f"Index to be removed is: {i}")
            print(f"List after removing index {i} : {temp_lst}")
            print()

    return count

# Example usage
list1 = [5, 5, 2, 5, 8]
list2 = [2, 1, 6, 4]

count_special1 = count_special_elements(list1)
print(f"Total number of special elements: {count_special1}")
print()

count_special2 = count_special_elements(list2)
print(f"Total number of special elements: {count_special2}")
Original List: [5, 5, 2, 5, 8]
Index to be removed is: 0
List after removing index 0 : [5, 2, 5, 8]

Original List: [5, 5, 2, 5, 8]
Index to be removed is: 1
List after removing index 1 : [5, 2, 5, 8]

Total number of special elements: 2

Original List: [2, 1, 6, 4]
Index to be removed is: 1
List after removing index 1 : [2, 6, 4]

Total number of special elements: 1

Write Python Program to create a dictionary with the key as the first character and value as a list of words starting with that character.

Example:
Input: Don’t wait for your feelings to change to take the action. Take the action and your feelings will change
Output:
{'D': ['Don’t'], 'w': ['wait', 'will'], 'f': ['for', 'feelings', 'feelings'], 'y': ['your', 'your'], 't': ['to', 'to', 'take', 'the', 'the'], 'c': ['change', 'change'], 'a': ['action.', 'action', 'and'], 'T': ['Take']} 

def create_dictionary(sentence):
    words = sentence.split()
    result_dict = {}

    for word in words:
        # Use the first character of the word as the key
        key = word[0]

        # Check if the key is already present in the dictionary
        if key in result_dict:
            result_dict[key].append(word)
        else:
            result_dict[key] = [word]

    return result_dict

# Example usage
input_sentence = "Don’t wait for your feelings to change to take the action. Take the action and your feelings will change"
output_dict = create_dictionary(input_sentence)

# Output the result
print("Input:", input_sentence)
print("Output:", output_dict)
Input: Don’t wait for your feelings to change to take the action. Take the action and your feelings will change
Output: {'D': ['Don’t'], 'w': ['wait', 'will'], 'f': ['for', 'feelings', 'feelings'], 'y': ['your', 'your'], 't': ['to', 'to', 'take', 'the', 'the'], 'c': ['change', 'change'], 'a': ['action.', 'action', 'and'], 'T': ['Take']}

Write a python program to update the password of any user given the above dictionary(d) which stores the username as the key of the dictionary and the username’s password as the value of the dictionary. print the updated dictionary and print the username and password according to ascending order of password length of the updated dictionary.

d={"student0":'Student@0',"student1":'Student@11',"student2":'Student@121', "student3":'Student@052',"student4":'Student@01278',"student5":'Student@0125', Student6":'Student@042', "student7":'Student@07800',"student8":'Student@012',  "student9":'Student@04789'}  

For the password updating of that username follow some instructions-

  • Give the three chances to user enter the correct username and password. If the user does not enter the correct username and password then display “enter correct password and username”. if the user does not enter the correct username and password in a given three chances then display “enter correct password and username” and “try after 24h”
  • If the user enters the correct username and password in a given three chances. Give the three chances to user enter a new password to update the password of that username. If the user enters a new password not follow the below format, then display “follow the password format”. if the user does not enter the password in a given format in a given three chances, then display “follow the password format” and “try after 24h”
  • The check, of whether the new password format is correct or wrong makes the user define a function. That user define a function to return True or False for password valid or not. That user define function return value used in this program for new password validation.

New password must have the below format:

  1. at least 1 number between 0 and 9
  2. at least 1 upper letter (between a and z)
  3. at least 1 lower letter (between A and Z)
  4. at least 1 special character out of @$_
  5. minimum length of the password is 8 and the maximum length is 15
  6. Do not use space and other special characters. Only uses @$_

If the new password follows the format of the password in a given three chances. then print the updated dictionary and print the username and password according to ascending order of password length of an updated dictionary. If the dictionary is not updated then take the old dictionary

def is_valid_password(password):
    # Function to check if the new password format is correct
    # Conditions: 1 number, 1 upper letter, 1 lower letter, 1 special character, length between 8 and 15
    has_digit = False
    has_lower = False
    has_upper = False
    has_special = False
    is_length_valid = 8 <= len(password) <= 15

    for char in password:
        if char.isdigit():
            has_digit = True
        elif char.islower():
            has_lower = True
        elif char.isupper():
            has_upper = True
        elif char in '@$_':
            has_special = True

    return has_digit and has_lower and has_upper and has_special and is_length_valid

def update_password(username, old_password, new_password):
    # Function to update the password for a given username
    if username in d and d[username] == old_password and is_valid_password(new_password):
        d[username] = new_password
        print("Password updated successfully.")
        return True
    else:
        print("Invalid username or old password.")
        return False

# Given dictionary
d = {"student0": 'Student@0', "student1": 'Student@11', "student2": 'Student@121', "student3": 'Student@052',
     "student4": 'Student@01278', "student5": 'Student@0125', "student6": 'Student@042', "student7": 'Student@07800',
     "student8": 'Student@012', "student9": 'Student@04789'}

# Input: User and Password Verification
username_attempts = 0
while username_attempts < 3:
    username_input = input("Enter username: ")
    password_input = input("Enter password: ")

    if username_input in d and d[username_input] == password_input:
        break
    else:
        print("Enter correct username and password.")
        username_attempts += 1

if username_attempts == 3:
    print("Try after 24h.")
else:
    # Input: New Password Verification
    password_attempts = 0
    while password_attempts < 3:
        new_password_input = input("Enter new password: ")

        if is_valid_password(new_password_input):
            if update_password(username_input, password_input, new_password_input):
                break
        else:
            print("Follow the password format.")
            password_attempts += 1

    if password_attempts == 3:
        print("Follow the password format. Try after 24h.")
        d = old_d  # Revert to the old dictionary

# Print the updated dictionary
print("Updated Dictionary:", d)

# Print username and password according to ascending order of password length
sorted_credentials = sorted(d.items(), key=lambda x: len(x[1]))
print("Username and Passwords in Ascending Order of Password Length:")
for username, password in sorted_credentials:
    print(f"Username: {username}, Password: {password}")
Enter username: student0
Enter password: Student@0
Enter new password: Rahul@0
Follow the password format.
Enter new password: Rahul_123@
Password updated successfully.
Updated Dictionary: {'student0': 'Rahul_123@', 'student1': 'Student@11', 'student2': 'Student@121', 'student3': 'Student@052', 'student4': 'Student@01278', 'student5': 'Student@0125', 'student6': 'Student@042', 'student7': 'Student@07800', 'student8': 'Student@012', 'student9': 'Student@04789'}
Username and Passwords in Ascending Order of Password Length:
Username: student0, Password: Rahul_123@
Username: student1, Password: Student@11
Username: student2, Password: Student@121
Username: student3, Password: Student@052
Username: student6, Password: Student@042
Username: student8, Password: Student@012
Username: student5, Password: Student@0125
Username: student4, Password: Student@01278
Username: student7, Password: Student@07800
Username: student9, Password: Student@04789